#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define LISTEN_PORT 8888
#define BUFFER_SIZE 1024
#define BLOCK_QUEUE_SIZE 100
#define SERVER_MSG "Hello Client, I'm Server."

int main() {
    int ret = -1;
    int listen_fd = -1;
    int client_fd = -1;
    char buff[BUFFER_SIZE] = {0};
    struct sockaddr_in server_addr = {0};
    struct sockaddr_in client_addr = {0};
    struct sockaddr *ptr_server_addr = (struct sockaddr *)&server_addr;
    struct sockaddr *ptr_client_addr = (struct sockaddr *)&client_addr;
    socklen_t client_addr_len = sizeof(client_addr);

    listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_fd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(LISTEN_PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    ret = bind(listen_fd, ptr_server_addr, sizeof(server_addr));
    if (ret == -1) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    ret = listen(listen_fd, BLOCK_QUEUE_SIZE);
    if (ret == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d ...\n", LISTEN_PORT);
    client_fd = accept(listen_fd, ptr_client_addr, &client_addr_len);
    if (client_fd == -1) {
        perror("accept");
        exit(EXIT_FAILURE);
    }
    printf("Client connected.\n");

    memset(buff, 0, BUFFER_SIZE);
    read(client_fd, buff, BUFFER_SIZE);
    printf("Client said: %s\n", buff);
    strcpy(buff, SERVER_MSG);
    write(client_fd, buff, BUFFER_SIZE);

    close(client_fd);
    close(listen_fd);
    return 0;
}
